<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-12-05 23:18:41
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-04-17 19:03:28
 * @FilePath: /vue-element-admin/src/views/storeSetup/product/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-12-04 16:07:30
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-12-10 01:31:24
 * @FilePath: /vue-element-admin/src/views/storeSetup/cineraryUrn/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container app-container-warehousing">
    <!-- 搜索区 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="物料">
          <el-input
            v-model="listQuery.name"
            placeholder=""
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="数量">
          <el-input
            v-model="listQuery.num"
            placeholder=""
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item label="单价">
          <el-input
            v-model="listQuery.price"
            placeholder=""
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item label="开始日期">
          <el-date-picker
            v-model="listQuery.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="listQuery.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd 23:59:59"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!-- <el-select
      v-model="listQuery.sort"
      style="width: 140px"
      class="filter-item"
      @change="handleFilter"
    >
      <el-option
        v-for="item in sortOptions"
        :key="item.key"
        :label="item.label"
        :value="item.key"
      />
    </el-select> -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        入库
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
    </div>
    <el-table  empty-text='暂无数据' :data="tableList" style="width: 100%; margin-top: 30px" border>
      <el-table-column align="center" label="店铺名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.shopName }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="物料名称" width="220">
        <template slot-scope="scope">
          {{ `${scope.row.name}(${scope.row.spec})` }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="库存数量" width="220">
        <template slot-scope="scope">
          {{ scope.row.num }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="单价" width="220">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="物料类型" width="220">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="规格" width="220">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="创建日期" width="220">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="220">
        <template slot-scope="scope">
          {{ scope.row.isInvalid }}
        </template>
      </el-table-column> -->

      <!-- <el-table-column align="center" label="备注" width="220">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="header-center" label="Description">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="Actions"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            入库记录
          </el-button>
          <el-button
            v-if="row.isInvalid == 0"
            size="mini"
            type="danger"
            @click="handleInvalidRecover(row, 1)"
          >
            作废
          </el-button>
          <el-button
            v-if="userInfo.isShopLeader !== 0 && row.isInvalid == 1"
            size="mini"
            type="success"
            @click="handleInvalidRecover(row, 0)"
          >
            恢复
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页区 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.limit"
      @pagination="getListQuery"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        label-width="120px"
        label-position="right"
        class="demo-form-inline"
        :rules="rules"
        :inline="true"
      >
        <el-form-item label="物料">
          <el-select
            v-model="temp.stockId"
            class="filter-item"
            placeholder="物料"
            @change="meteralChange"
          >
            <el-option
              v-for="item in meterialDatas"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="单价">
          <el-input
            disabled
            v-model.number="temp.price"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="单价"
          />
        </el-form-item>
        <el-form-item label="数量" prop="">
          <el-input
            v-model.number="temp.num"
            :autosize="{ minRows: 2, maxRows: 4 }"
            :placeholder="numPlaceholder"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
         确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      fullscreen
      title="入库记录"
      :visible.sync="dialogFormVisibleForTable"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-width="120px"
        label-position="right"
        class="demo-form-inline"
        :rules="rules"
        :inline="true"
      >
        <el-table
          :data="outofstockDetailList"
          size="mini"
          style="width: 100%; margin-top: 30px"
          border
        >
          <el-table-column align="center" label="店铺名称" width="220">
            <template slot-scope="scope">
              {{ scope.row.shopName }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="物料名称" width="220">
            <template slot-scope="scope">
              {{ `${scope.row.stockName}(${scope.row.stockSpec})` }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="已入库数量" width="220">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="单价" width="220">
            <template slot-scope="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="规格" width="220">
            <template slot-scope="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="创建日期" width="220">
            <template slot-scope="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" width="220">
            <template slot-scope="scope">
              {{ scope.row.isInvalid == 0 ? "作废" : "正常" }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="备注" width="220">
            <template slot-scope="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
          <!-- <el-table-column align="header-center" label="Description">
            <template slot-scope="scope">
              {{ scope.row.price }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="230"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{ row, $index }">
              <el-button
                v-if="row.isInvalid == 0"
                size="mini"
                type="danger"
                @click="handleInvalidRecover(row, 1)"
              >
                作废
              </el-button>
              <el-button
                v-if="userInfo.isShopLeader !== 0 && row.isInvalid == 1"
                size="mini"
                type="success"
                @click="handleInvalidRecover(row, 0)"
              >
                恢复
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleForTable = false">
         取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
         确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from "path";
import { deepClone } from "@/utils";
import {
  getListQuery,
  create,
  update,
  deleteData,
  getMaterialListQuery,
  invalidRecoverApi,
  outofstockDetailListApi,
} from "@/api/warehousing";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { mapState } from "vuex";

export default {
  components: { Pagination },

  data() {
    const validateNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入数字"));
      } else if (isNaN(value)) {
        callback(new Error("请输入有效的数字"));
      } else if (value > this.numValue) {
        callback(
          new Error(
            `当前物料数量为${this.numValue},入库数量不可超出当前物料数量`
          )
        );
      } else {
        callback();
      }
    };
    return {
      outofstockDetailList: "",
      numValue: 0,
      rules: {
        num: [
          { required: true, message: "type is required", trigger: "blur" },
          { validator: validateNumber, trigger: "blur" },
        ],
      },
      numPlaceholder: "", //库存数量
      stockNum: 0, //库存数量
      meterialDatas: [], //物料数据
      tableList: [],
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        // type: "入库",
      },
      total: 0,
      dialogFormVisibleForTable: false,
      listLoading: true,
      temp: {
        // type: "入库",
        remark: "",
        price: "",
        stockId: "",
        num: "",
        // meterialValue:''
      },
      downloadLoading: false,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "新增",
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  created() {
    this.getListQuery();
    this.getMaterialListQuery();
  },

  methods: {
    handleInvalidRecover(row, value) {
      invalidRecoverApi({ id: row.id, isInvalid: value }).then(() => {
        this.$notify({
          title: "Success",
          message: "作废 Successfully",
          type: "success",
          duration: 2000,
        });
        this.getListQuery();
      });
    },
    meteralChange(id) {
      const results = this.meterialDatas.filter((item) => item.id === id)[0];
      this.numValue = results.num;
      this.numPlaceholder = `物品数量${results.num}`;
      this.stockNum = results.stockNum;
      this.temp.price = results.price;
      this.temp.stockId = results.id;
    },
    handleUpdate(row) {
      outofstockDetailListApi({ stockId: row.id, type: "入库" }).then(
        (response) => {
          this.outofstockDetailList = response.data;
          this.outofstockDetailTotal = response.data.total;
          this.listLoading = false;
        }
      );

      this.meterialDatas;
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisibleForTable = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row, index) {
      deleteData(row.id).then((response) => {
        this.listLoading = true;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
        this.getListQuery();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          const tempData = Object.assign({}, this.temp);
          tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          update(tempData).then(() => {
            // this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
            this.listLoading = false;
            this.getListQuery();
          });
        }
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          create(this.temp).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
            this.getListQuery();
          });
        }
      });
    },
    resetTemp() {
      this.temp = {
        type: "入库",
        remark: "",
        price: "",
        stockId: "",
        num: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    getMaterialListQuery() {
      getMaterialListQuery().then((response) => {
        this.meterialDatas = response.data;
      });
    },
    getListQuery() {
      this.listLoading = true;
      this.listQuery.status=0
      getListQuery(this.listQuery).then((response) => {
        this.tableList = response.data.records;
        this.total = response.data.total;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.listQuery.name=this.listQuery?.name?.replace(/\(.*?\)/g, "");

      this.getListQuery();
    },
    handleAdd() {},
    formatJson(filterVal) {
      return this.tableList.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["物料", "价格", "数量", "创建时间", "备注"];
        const filterVal = ["name", "price", "num", "createTime", "remark"];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list",
        });
        this.downloadLoading = false;
      });
    },
  },
};
</script>

<style lang="scss" >
.app-container-warehousing {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-form-item__error {
    position: relative;
  }
}
</style>
